package com.xiaoming.tranAnno.aop;

import com.xiaoming.tranAnno.utils.TransactionUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

@Aspect
@Component
public class TransactionAop {

    @Autowired
    private TransactionUtil transactionUtil;

    @Around(value = "@annotation(com.xiaoming.tranAnno.aop.MyTransactional)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        TransactionStatus transactionStatus = null;
        try{
            transactionStatus = transactionUtil.begin();
            Object result = proceedingJoinPoint.proceed();
            transactionUtil.commit(transactionStatus);
            return result;
        }catch (Throwable e){
            e.printStackTrace();
            if(transactionStatus != null){
                transactionUtil.rollback(transactionStatus);
            }
            return "FAIL";
        }
    }

}
